package com.gjy.nwpufindseats.Fragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.client.ClientProtocolException;

import com.gjy.nwpufindseats.baseData.Global;
import com.gjy.nwpufindseats.util.AESEncryptor;
import com.gjy.nwpufindseats.util.JwNetSpider;
import com.gjy.nwpufindseats.util.NetInfo;
import com.gjy.nwpufindseats.MainActivity;
import com.gjy.nwpufindseats.R;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;


@SuppressLint({ "ShowToast", "CommitPrefEdits" })
public class Fragment_login extends Fragment implements OnClickListener{
	public static SharedPreferences preferences;
	public static SharedPreferences methodPreferences;
	public static SharedPreferences passwordPreferences;
	public static Editor editor;
	public static Editor methodEditor;
	public static Editor passwordEditor;
	public static TextView login;
	private EditText xh;//学号输入框
	private ImageButton ib_spinner;
	private MyAdapter adapter;
	private EditText password;//密码输入框
	private RadioButton jwButton;
	private RadioButton digitalButton;
	private CheckBox checkBox;//是否记住密码多选框
	public static NetInfo netInfo = new NetInfo();
	public static boolean loginFailure = false;//默认登录成功，检测登录失败
	public static String xhString;
	public static String passwordString;
	public static Context mainContext;
	public static View view;
	public static Boolean end = false;
	public static ProgressDialog mydialog;
	private ArrayList<String> userXh = new ArrayList<String>();
	private PopupWindow pop;
	public static Map<String, String> passwordMap;
	public static Map<String, Boolean> methodMap;
	
    
	@SuppressLint("CommitPrefEdits")
	@SuppressWarnings("unchecked")
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    		Bundle savedInstanceState) {
    	view = inflater.inflate(R.layout.fragment_login, container, false);
    	mainContext = getActivity();
    	if(!netInfo.isNetConnect(mainContext))
    	{
    		Fragment newContent = new Fragment_netFailure();
    		switchFragment(newContent);
    		return view;
    	}
    	//getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    	login = (TextView) view.findViewById(R.id.login);
    	login.setOnClickListener(this);
    	xh = (EditText) view.findViewById(R.id.xh);
    	password = (EditText) view.findViewById(R.id.password);  
    	jwButton = (RadioButton) view.findViewById(R.id.jw);
    	digitalButton = (RadioButton) view.findViewById(R.id.digital);
    	checkBox = (CheckBox) view.findViewById(R.id.savePwd);
    	preferences=getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
    	passwordPreferences=getActivity().getSharedPreferences("password", Context.MODE_PRIVATE);
    	methodPreferences=getActivity().getSharedPreferences("method", Context.MODE_PRIVATE);
    	editor = preferences.edit();
		passwordEditor = passwordPreferences.edit();
		methodEditor = methodPreferences.edit();
    	jwButton.setChecked(false);
    	digitalButton.setChecked(true);
		passwordMap=(Map<String, String>) passwordPreferences.getAll();
		methodMap= (Map<String, Boolean>) methodPreferences.getAll();
    	initData();
		initView(view);
    	return view;
    }
     
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		if("".equals( xh.getText().toString()) || "".equals(password.getText().toString()))
		{
			Toast.makeText(getActivity(), "哦，您忘输其中一项了吧。。。", Toast.LENGTH_SHORT).show();
		}
		else{
			
			end = false;
			xhString = xh.getText().toString();
			passwordString=password.getText().toString();
			Fragment newContent = new Fragment_login_info();
			Thread tProgress = new Thread()
	    	{
	    		public void run()
	    		{
	    			while (!end) //登录行为未结束，进度条持续
	                {
	    				Looper.prepare();
	    				mydialog=ProgressDialog.show(getActivity(), "正在登录", "忍受一下吧，毕竟是教务网。\n数字工大登录操作较为复杂，速度更慢。",true);
	    				mydialog.setCancelable(true);           
	                    mydialog.show();
	                    Looper.loop();
	                } 
	    		}
	    		
	    	};
	    	tProgress.start();
			Thread t = new Thread(){
				JwNetSpider jwNetSpider=new JwNetSpider();
				public void run(){	
					
					editor = preferences.edit();
					passwordEditor = passwordPreferences.edit();
					methodEditor = methodPreferences.edit();
					if(jwButton.isChecked())
					{
						editor.putBoolean("method", true);//true代表教务网登录
					}
					else {
						editor.putBoolean("method", false);//false代表数字工大登录
					}
					editor.commit();//提交数据，便于之后爬虫检测登录方式
					try {
						if(!jwNetSpider.firstLogin(mainContext,xhString, passwordString))
						{
							loginFailure = true;		
							
						}
						else 
						{
							Looper.prepare();
							loginFailure = false;
							
						}
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					end = true;//登录行为结束
					mydialog.dismiss();
				}				
			};
			t.start();
			try {
				t.join();
				if(!loginFailure)//登录成功！
				{					
					//隐藏输入法
					InputMethodManager imm = 
							(InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
	                imm.hideSoftInputFromWindow(login.getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
					Toast.makeText(mainContext, "登陆成功！", Toast.LENGTH_SHORT).show();
					
					editor.putString("xh", xhString);
					try {
						//对输入框的密码进行加密
						passwordString = AESEncryptor.encrypt(Global.rawKey, passwordString);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
					if("0".equals(preferences.getString("password", "0")))
						//如果没有保存的密码，说明没有使用数字工大。则返回为0。若不为0，则说明已经将数字工大登录教务的密码保存
						//使用的教务方式，将教务密码保存
					{
						editor.putString("password", passwordString);
					}	
					else {
						editor.putString("dPassword", passwordString);
					}
					editor.commit();//提交修改
					if(!checkBox.isChecked())
					{
						Global.savePwdBoolean = false;
					}
					else {//选择了记住密码，密码和方式存向用户库
						methodEditor.putBoolean(xhString,preferences.getBoolean("method", true));
						passwordEditor.putString(xhString, passwordString);//账户库无论怎样，也仅仅保存登录密码
						methodEditor.commit();
						passwordEditor.commit();
					}
					//登录成功，刷新当前页面的静态变量值，即两个MAP和学号的动态数组
					//passwordMap=(Map<String, String>) passwordPreferences.getAll();
					//methodMap= (Map<String, Boolean>) methodPreferences.getAll();
			    	//initData();
			    	
					if (newContent != null)
						switchFragment(newContent);
				}
				else{
					if(JwNetSpider.axgdBoolean)//网页打开正常，只能是密码错误
					{
						Toast.makeText(mainContext, "用户名或密码错误，请重试。。。", Toast.LENGTH_SHORT).show();
					}
					else{
						Toast.makeText(mainContext, "网速不给力，无法得到认证！", Toast.LENGTH_SHORT).show();
						JwNetSpider.axgdBoolean=true;//恢复为true，下次给出正确提醒
					}
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}		
	}
	
	@SuppressWarnings({ "rawtypes" })
	private void initData() //仅仅得到用户列表即可，至于登陆方法和密码在点击之后再进行操作
	{ 
		Iterator<Entry<String, Boolean>> it = methodMap.entrySet().iterator();
			while(it.hasNext()){
			Entry entry = it.next();			
			userXh.add(entry.getKey().toString());//返回与此项对应的键
			}	
		}
	
	private void initView(View view) {
		xh = (EditText) view.findViewById(R.id.xh);
		ib_spinner = (ImageButton) view.findViewById(R.id.ib_spinner);
		
		ib_spinner.setOnClickListener(new OnClickListener() {
			




			@Override
			public void onClick(View v) {
				//隐藏输入法
				InputMethodManager imm = 
						(InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(login.getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
				//弹出下拉列表
				ListView listView = new ListView(getActivity().getApplicationContext());
				listView.setCacheColorHint(0x00000000);//滑动时 不变色
				listView.setVerticalScrollBarEnabled(false);
				listView.setDividerHeight(4);
				
				adapter = new MyAdapter();
				listView.setAdapter(adapter);

				
				pop = new PopupWindow(listView, xh.getWidth(), 450, true);

				//pop隐藏
				pop.setBackgroundDrawable(new ColorDrawable(0x00000000));
				//pop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
				//pop.setSoftInputMode(INPUT_METHOD_NOT_NEEDED);
				pop.showAsDropDown(xh, 0, -5);
			}
		});
	}
    private void switchFragment(Fragment fragment) {
		if (getActivity() == null)
			return;	
			MainActivity ra = (MainActivity) getActivity();
			ra.switchContent(fragment);
		
	}
    
    class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return userXh.size();
		}

		@Override
		public Object getItem(int position) {
			return userXh.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			//第一种：
//			View view = View.inflate(getApplicationContext(), R.layout.item, null);
			//第二种：
			LayoutInflater inflater = LayoutInflater.from(getActivity().getApplicationContext());
			View view = inflater.inflate(R.layout.user_item, parent, false);
			
			TextView user_xh = (TextView) view.findViewById(R.id.user_xh);
			ImageButton delete = (ImageButton) view.findViewById(R.id.delete);
			
			user_xh.setText(userXh.get(position));
			
			user_xh.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					xh.setText(userXh.get(position));
					String decryptPassword;
					try {//解密，并写入输入框
						decryptPassword = AESEncryptor.decrypt(Global.rawKey, passwordMap.get(userXh.get(position)));
						password.setText(decryptPassword);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}					
					if(methodMap.get(userXh.get(position)))
					{
						jwButton.setChecked(true);
						digitalButton.setChecked(false);						
					}
					else {
						jwButton.setChecked(false);
						digitalButton.setChecked(true);		
					}
					
					pop.dismiss();
					
				}
			});
			
			delete.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dialog(position);					
				}
			});
			
			return view;
		}
		
		public void dialog(final int position) {
			  AlertDialog.Builder builder = new Builder(getActivity());
			  
			  builder.setTitle("提示");
			  builder.setMessage("确认删除该帐号的登陆记录吗？");
			  //不同的监听器
			  builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() {
				   @Override
				   public void onClick(DialogInterface dialog, int which) {
						methodEditor.remove(userXh.get(position).toString());
						passwordEditor.remove(userXh.get(position).toString());
						methodEditor.commit();
						passwordEditor.commit();
						userXh.remove(position);
						adapter.notifyDataSetChanged();
				    dialog.dismiss();
				    Toast.makeText(getActivity(), "清除成功！", Toast.LENGTH_SHORT).show();
				   }

			   });
			  builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
			   @Override
			   public void onClick(DialogInterface dialog, int which) {
			    dialog.dismiss();
			   }
			  });
			  builder.create().show();
			}
		
	}
	
    
}
